package com.itmake.sample.xss.config;

import cn.hutool.core.util.ArrayUtil;
import com.itmake.sample.xss.filter.XssFilter;
import com.itmake.sample.xss.property.XssProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置
 *
 * @author Amjacks
 * @since 2023/08/10
 */
@Configuration
public class XssConfig {

    @Autowired
    private XssProperty xssProperty;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(value = "config.xss.enabled", havingValue = "true")
    public FilterRegistrationBean xssFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns("/*");
        registration.setName("xssFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        // 传递参数
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", ArrayUtil.join(xssProperty.getExcludeUrls().toArray(), ","));
        registration.setInitParameters(initParameters);
        return registration;
    }
}
